package com.tsj.model.utils;

import org.apache.poi.ss.usermodel.PictureData;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellAddress;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorksheet;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author taoshujian
 * @version 1.0
 * @since 2025-10-26 23:54:56
 */
public class ExcelTest1 {
    public static void main(String[] args) throws IOException, ParserConfigurationException, SAXException {
        String url = "D://1.xlsx";
        String outputDir = "D://";
        FileInputStream file = new FileInputStream(new File(url));


        Workbook workbook = new XSSFWorkbook(file);
        List<? extends PictureData> allPics = workbook.getAllPictures();
        // 建立“图片数据→索引”的映射（用于后续匹配）
        Map<String, Integer> picDataToIndex = new HashMap<>();
        for (int i = 0; i < allPics.size(); i++) {
            PictureData data = allPics.get(i);
            // 用图片数据的哈希值作为key（避免直接比较字节数组）
            String hash = Arrays.hashCode(data.getData()) + "";
            picDataToIndex.put(hash, i);
        }

        // 遍历所有工作表
        for (int sheetIdx = 0; sheetIdx < workbook.getNumberOfSheets(); sheetIdx++) {
            XSSFSheet sheet = (XSSFSheet) workbook.getSheetAt(sheetIdx);
            CTWorksheet ctSheet = sheet.getCTWorksheet();
            String xmlContent = ctSheet.xmlText(); // 获取工作表XML内容

            // 解析XML
            Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                    .parse(new ByteArrayInputStream(xmlContent.getBytes(StandardCharsets.UTF_8)));

            // 查找所有图片节点（标签可能为<xdr:pic>或<drawing>，需根据实际XML调整）
            NodeList picNodes = doc.getElementsByTagName("xdr:pic");
            for (int i = 0; i < picNodes.getLength(); i++) {
                Element picElem = (Element) picNodes.item(i);
                // 1. 获取图片ID（对应资源池中的索引）
                String picId = picElem.getAttribute("blipFill/blip/@r:embed"); // 需根据XML结构调整XPath

                // 2. 获取图片所在单元格（通过锚点坐标解析）
                Element anchorElem = (Element) picElem.getElementsByTagName("xdr:twoCellAnchor").item(0);
                int rowIdx = Integer.parseInt(anchorElem.getAttribute("from/r")); // 起始行
                int colIdx = Integer.parseInt(anchorElem.getAttribute("from/c")); // 起始列
                String cellRef = new CellAddress(rowIdx, colIdx).formatAsString();

                // 3. 关联图片数据（通过ID匹配资源池中的图片）
                PictureData picData = allPics.get(Integer.parseInt(picId));
                System.out.println("单元格 " + cellRef + " 包含图片：" + picData.suggestFileExtension());
            }
        }
    }
}
